<template>
  <div>
    <!-- 主表单渲染，保持原有逻辑不变 -->
    <div :style="{ padding: `${layout.视图边距}px` }">
      <a-row :gutter="layout.左右间距">
        <template v-for="(c, i) in columns" >
          <a-col :offset="c.offset" :span="c.span" :key="`column${i}`">
            <div :class="layout.标签对齐 === 'top' ? '' : 'flx-s'" :style="{ marginBottom: `${layout.上下间距}px` }">
              <div
                :class="layout.标签对齐 === 'right' ? 'tar' : 'tal'"
                class="mr10"
                :style="{ width: `${layout.标签宽度}px` }"
              >
                <span class="mr5 error" v-if="c.isNeed">*</span>{{ c.name }}
              </div>
              <div class="flx-1" :class="layout.标签对齐 === 'top' ? 'mt10' : ''">
                <div v-if="obj !== null">
                  <div class="flx-s">
                    <div v-if="c.compType === '文本'">{{ c.defaultVal }}</div>
                    <div v-if="c.compType==='单行文本'" class="wfull">
                      <div class="flx-s wfull" v-if="c.extra&&c.extra.suffix==='btn'">
                        <ZgInput :disabled="c.disabled" v-model="obj[c.code]" :placeholder="(c.extra&&c.extra.placeholder)||''" :maxLength="c.extra&&c.extra.maxLength">
                        </ZgInput>
                        <ZgButton class="ml10" :icon="c.extra.icon" @click="inputClick(obj)">{{ c.extra.btn }}</ZgButton>
                      </div>
                      <ZgInput v-else :disabled="c.disabled" v-model="obj[c.code]" :placeholder="(c.extra&&c.extra.placeholder)||''" :maxLength="c.extra&&c.extra.maxLength">
                        <div slot="suffix" v-if="c.extra&&c.extra.suffix==='icon'">
                          <i class="cpt fa" :class="`fa-${c.extra.icon}`" @click="inputClick(obj)"/>
                        </div>
                      </ZgInput>
                    </div>
                    <ZgSelect :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '下拉选择'" :options="c.extra.下拉选项"></ZgSelect>
                    <ZgRadio :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '单选'" :options="c.extra.选项"></ZgRadio>
                    <ZgNumber :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '整数'" />
                    <ZgNumber :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '浮点数'" isFloat />
                    <ZgCheckbox :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '单选框'" />
                    <ZgMultiple :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '多选'" :code="c.extra.字典类型" />
                    <ZgDatePicker :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '日期'" />
                    <ZgDateTimePicker :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '日期时间'" />
                    <ZgDictionary
                      v-model="obj[c.code]"
                      v-if="c.compType === '字典'"
                      :code="c.extra.字典类型"
                      :disabled="c.disabled"
                    />
                    <ZgSwitch :disabled="c.disabled" v-model="obj[c.code]" v-if="c.compType === '开关'" />
                    <ZgTextarea
                      v-model="obj[c.code]"
                      v-if="c.compType === '多行文本'"
                      :rows="parseInt(c.extra.行数)"
                      :maxLength="c.extra&&c.extra.maxLength"
                      :disabled="c.disabled"
                    />
                    <ZgTinymce
                      v-model="obj[c.code]"
                      v-if="c.compType === '富文本'"
                      :height="parseInt(c.extra.高度)"
                    />
                    <ZgUpImg v-model="obj[c.code]" v-if="c.compType === '图片'" />
                    <ZgUpImgs v-model="obj[c.code]" v-if="c.compType==='多图'" :note="c.extra.note" />
                    <div v-if="c.unit" class="ml10">{{ c.unit }}</div>
                  </div>
                  <div v-if="c.note&&c.note.length>0" class="info fs10 mt5">
                    {{ c.note }}
                  </div>
                </div>
              </div>
            </div>
          </a-col>
          <a-col v-if="c.divider&&c.divider.length>0" :span="24" :key="`column_bar${i}`">
            <a-divider>{{ c.divider }}</a-divider>
          </a-col>
        </template>
      </a-row>
    </div>
    <!-- 子表单tabs渲染，v-model和key都用id，数据双向绑定 -->
    <a-tabs v-if="subDiyForm.length > 0" v-model="activeSubTab" class="mt20">
      <a-tab-pane v-for="(sub) in subDiyForm" :key="sub.id" :tab="sub.name">
        <a-table :data-source="getSubRows(sub.id)" :pagination="false" :rowKey="(record, idx) => idx" bordered>
          <a-table-column v-for="c in sub.columns" :key="c.code" :title="c.name" :dataIndex="c.code">
            <template slot-scope="text, record">
              <div v-if="c.compType === '文本'">{{ c.defaultVal }}</div>
              <div v-else-if="c.compType==='单行文本'">
                <ZgInput :disabled="c.disabled" v-model="record[c.code]" :placeholder="(c.extra&&c.extra.placeholder)||''" :maxLength="c.extra&&c.extra.maxLength" />
              </div>
              <ZgSelect v-else-if="c.compType === '下拉选择'" :disabled="c.disabled" v-model="record[c.code]" :options="c.extra.下拉选项"></ZgSelect>
              <ZgRadio v-else-if="c.compType === '单选'" :disabled="c.disabled" v-model="record[c.code]" :options="c.extra.选项"></ZgRadio>
              <ZgNumber v-else-if="c.compType === '整数'" :disabled="c.disabled" v-model="record[c.code]" />
              <ZgNumber v-else-if="c.compType === '浮点数'" :disabled="c.disabled" v-model="record[c.code]" isFloat />
              <ZgCheckbox v-else-if="c.compType === '单选框'" :disabled="c.disabled" v-model="record[c.code]" />
              <ZgMultiple v-else-if="c.compType === '多选'" :disabled="c.disabled" v-model="record[c.code]" :code="c.extra.字典类型" />
              <ZgDatePicker v-else-if="c.compType === '日期'" :disabled="c.disabled" v-model="record[c.code]" />
              <ZgDateTimePicker v-else-if="c.compType === '日期时间'" :disabled="c.disabled" v-model="record[c.code]" />
              <ZgDictionary v-else-if="c.compType === '字典'" v-model="record[c.code]" :code="c.extra.字典类型" :disabled="c.disabled" />
              <ZgSwitch v-else-if="c.compType === '开关'" :disabled="c.disabled" v-model="record[c.code]" />
              <ZgTextarea v-else-if="c.compType === '多行文本'" v-model="record[c.code]" :rows="parseInt(c.extra.行数)" :maxLength="c.extra&&c.extra.maxLength" :disabled="c.disabled" />
              <ZgTinymce v-else-if="c.compType === '富文本'" v-model="record[c.code]" :height="parseInt(c.extra.高度)" />
              <ZgUpImg v-else-if="c.compType === '图片'" v-model="record[c.code]" />
              <ZgUpImgs v-else-if="c.compType==='多图'" v-model="record[c.code]" :note="c.extra.note" />
              <div v-else-if="c.unit" class="ml10">{{ c.unit }}</div>
            </template>
          </a-table-column>
          <a-table-column key="action" title="操作" fixed="right" :width="80">
            <template slot-scope="text, record, rowIdx">
              <a-button type="link" @click="addSubRow(sub.id)" v-if="getSubRows(sub.id).length === 1 || rowIdx === getSubRows(sub.id).length - 1">
                <a-icon type="plus" />
              </a-button>
              <a-button type="link" @click="removeSubRow(sub.id, rowIdx)">
                <a-icon type="minus" />
              </a-button>
            </template>
          </a-table-column>
        </a-table>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script>
import { columnMixin } from '@/views/autoform/column/js/mixin'

export default {
  mixins: [columnMixin],
  props: {
    inputClick: {
      type: Function,
      default: (t) => {}
    },
    formView: {
      type: Object,
      default: () => {
        return {}
      }
    },
    formulas: {
      type: Array,
      default: () => [
        { triggerMode: '初始化时', name: '公式1', content: 'console.log("init");' },
        { triggerMode: '数据变化时', name: '公式2', content: 'console.log("update");' },
        { triggerMode: '提交时', name: '公式3', content: 'console.log("submit");' }
      ]
    },
    validUrl: {
      type: String,
      default: ''
    },
    saveUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      obj: null,
      columns: [],
      layout: {
        视图边距: 10,
        标签宽度: 120,
        标签对齐: 'right',
        左右间距: 10,
        上下间距: 10
      },
      activeSubTab: '',
      subObjList: [], // 变为二维数组，每个子表为多行
      subDiyForm: []
    }
  },
  watch: {
    formView: {
      handler (newVal, oldVal) {
        console.log(newVal, oldVal)
        this.initData()
      },
      deep: true,
      immediate: true
    },
    obj: {
      handler (newVal, oldVal) {
        this.$emit('input', { ...newVal })
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          this.doFormula(
            this.formulas.filter((t) => t.triggerMode === '数据变化时')
          )
        }
      },
      deep: true,
      immediate: true
    },
    subObjList: {
      handler (newVal) {
        this.$emit('subInput', JSON.parse(JSON.stringify(newVal)))
      },
      deep: true
    }
  },
  methods: {
    open (json) {
      if (json) {
        this.obj = Object.assign({}, this.obj, json)
        this.$emit('input', { ...this.obj })
      }
    },
    getSubRows (id) {
      const idx = this.subDiyForm.findIndex(sub => sub.id === id)
      return idx !== -1 ? this.subObjList[idx] : []
    },
    getSubObj (id) {
      // 兼容旧用法，返回第一行
      const rows = this.getSubRows(id)
      return rows.length > 0 ? rows[0] : null
    },
    addSubRow (id) {
      const idx = this.subDiyForm.findIndex(sub => sub.id === id)
      if (idx !== -1) {
        const columns = this.subDiyForm[idx].columns
        const newRow = {}
        columns.forEach(col => {
          newRow[col.code] = this.initDefaultVal(col.defaultVal)
        })
        this.subObjList[idx].push(newRow)
      }
    },
    removeSubRow (id, rowIdx) {
      const idx = this.subDiyForm.findIndex(sub => sub.id === id)
      if (idx !== -1) {
        this.subObjList[idx].splice(rowIdx, 1)
      }
    },
    initData () {
      if (this.formView.active) {
        this.$http.post('/zg-autoform/view/get', { viewId: this.formView.active, stepInstCode: this.formView.stepInstCode }, (res) => {
          // 主表
          if (res.diyView.layout) {
            this.layout = JSON.parse(res.diyView.layout)
          }
          if (res.allColumns && res.allColumns.length > 0) {
            this.columns = res.viewInfoList
            this.obj = res.allColumns.reduce((x, item) => {
              this.compType = item.compType
              x[item.code] = this.initDefaultVal(item.defaultVal)
              return x
            }, {})
            this.$emit('input', { ...this.obj })
          }
          this.doFormula(
            this.formulas.filter((t) => t.triggerMode === '初始化时')
          )
          // 子表
          if (Array.isArray(res.subDiyForm)) {
            this.subDiyForm = res.subDiyForm
            this.subObjList = res.subDiyForm.map(sub => {
              // 如果有columnData则直接用其内容，否则用默认值
              if (Array.isArray(sub.columnData) && sub.columnData.length > 0) {
                // 只保留columns中定义的字段
                return sub.columnData.map(row => {
                  const obj = {}
                  if (Array.isArray(sub.columns)) {
                    sub.columns.forEach(col => {
                      obj[col.code] = row[col.code] !== undefined ? row[col.code] : this.initDefaultVal(col.defaultVal)
                    })
                  }
                  console.log(obj, 'obj')
                  return obj
                })
              } else {
                const obj = {}
                if (Array.isArray(sub.columns)) {
                  sub.columns.forEach(col => {
                    obj[col.code] = this.initDefaultVal(col.defaultVal)
                  })
                }
                return [obj]
              }
            })
            this.activeSubTab = res.subDiyForm.length > 0 ? res.subDiyForm[0].id : ''
          } else {
            this.subDiyForm = []
            this.subObjList = []
            this.activeSubTab = ''
          }
        })
      }
    },
    doFormula (formulas) {
      if (!formulas || formulas.length === 0) {
        return
      }
      const arr = []
      formulas.forEach((t) => {
        try {
          // eslint-disable-next-line no-eval
          eval(t.content)
        } catch (e) {
          arr.push(t)
        }
      })
      if (arr.length > 0) {
        this.$error({ title: `有${arr.length}个公式执行错误：${arr.map((t) => t.name).join('、')}` })
        return false
      } else {
        return true
      }
    },
    save () {
      // 验证接口设置
      if (this.saveUrl.length === 0) {
        this.$error({ title: `未设置保存接口` })
        return
      }
      // 验证必填项
      for (const i in this.columns) {
        const column = this.columns[i]
        const value = this.obj[column.code]
        if (!column.isNeed) {
          continue
        }
        if (['单选框', '开关'].includes(column.compType)) {
          continue
        } else if (['整数', '浮点数'].includes(column.compType)) {
          if (!value || value === 0) {
            this.$error({ title: `${column.name}不能为0` })
            return
          }
        } else {
          if (!value || value.length === 0) {
            this.$error({ title: `${column.name}为必填项` })
            return
          }
        }
      }
      // 验证正则，只验证单行文本
      for (const i in this.columns) {
        const column = this.columns[i]
        const value = this.obj[column.code]
        if (column.compType === '单行文本' && column.regex && column.regex.length > 0) {
          const reg = new RegExp(column.regex)
          if (!reg.test(value)) {
            this.$error({ title: column.errorMsg })
            return
          }
        }
      }
      // 提交前执行公式
      this.doFormula(
        this.formulas.filter((t) => t.triggerMode === '提交时')
      )
      // 远程验证接口
      const param = Object.assign({}, this.obj)
      if (this.validUrl && this.validUrl.length > 0) {
        this.$http.post(
          this.validUrl,
          param,
          () => {
            this.realSave(param)
          },
          (exp) => {
            this.$error({ title: '远程验证接口调用失败，请检查接口地址' })
          }
        )
      } else {
        this.realSave(param)
      }
    },
    realSave (param) {
      // 组装子表数据
      if (Array.isArray(this.subDiyForm) && this.subDiyForm.length > 0) {
        param.subInfo = this.subDiyForm.map((sub, idx) => ({
          subTableCode: sub.code,
          subTableData: this.subObjList[idx] || []
        }))
      }
      if (this.saveUrl.includes('update')) {
        param.id = this.formView.bizFormId
      }
      this.$http.post(this.saveUrl + this.formView.bizzTable, param, (res) => {
        this.$emit('ok', res)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
